<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base href="/">
    <!--在此页面定义根路径-->

    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="layui/css/layui.css">
<!--http://layui.apixx.net/doc/index.html-->

<!--http://layui.apixx.net/doc/modules/table.html    -->

<body>

<!--数据列表-->
<table class="layui-table" lay-data="{url:'goods/list', page:true, id:'datalist',toolbar:'#toptools'}" lay-filter="datalist">
    <thead>
    <tr>
        <th lay-data="{field:'id', width:50}">ID</th>
        <th lay-data="{field:'name', width:150}">名称</th>
        <th lay-data="{field:'price', width:100}">价格</th>
        <th lay-data="{field:'originalprice', width:100}">原价</th>
        <th lay-data="{field:'info', width:125}">简介</th>
        <th lay-data="{field:'category_id', width:75}">所属类id</th>
<!--    <th lay-data="{templet:'#parentTpl', width:125}">所属类</th>-->
<!--    <th lay-data="{field:'defaultimg', width:125}">图片</th>-->
        <th lay-data="{templet:'#imgTpl', width:75}">缩略图</th>

        <th lay-data="{toolbar:'#linetools'}">操作</th>
    </tr>
    </thead>
</table>

<!--父级分类自定义模板-->
<!--<script type="text/html" id="parentTpl">-->
<!--    <span>{{ d.parent.name }}</span>-->
<!--</script>-->

<!--图片列自定义模板-->
<script type="text/html" id="imgTpl" class="">
    <!--    src属性中就要写上当前行的imgurl属性-->
    <img src="{{d.defaultimg}}" style="height: 30px;width: 30px;">

</script>


<!--行内工具栏-->
<script id="linetools" type="text/html">
    <button type="button" class="layui-btn" lay-event="edit">修改</button>
    <button type="button" class="layui-btn" lay-event="manage">图片管理</button>
    <button type="button" class="layui-btn" lay-event="del">删除</button>
</script>

<!--头部工具栏-->
<script id="toptools" type="text/html">
    <div class="layui-form-item">
        <div class="layui-input-inline">
            <input type="text" name="text" placeholder="请输入查询内容" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-input-inline">
            <button type="button" class="layui-btn" lay-event="check">查询</button>
            <button type="button" class="layui-btn" lay-event="add">新增</button>
        </div>
    </div>
</script>

<!--新增数据表单-->
<div style="display: none" id="addWin" lay-filter="addWin" class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline">
            <input type="text" name="name" required lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
            <!--表单验证：http://layui.xhcen.com/doc/dataForm.html#verify-->
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" required lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">简介</label>
        <div class="layui-input-inline">
            <input type="text" name="info" required lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">所属类</label>
        <div class="layui-input-inline">
            <select name="category_id">
                <option value="-1">请选择分类</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-inline">
            <img src="easyfile/upload.png" _id="addupload" style="width: 100px;height: 100px;cursor: pointer">
            <input type="hidden" _id="addimgurl" name="defaultimg" lay-verify="easyimg">
        </div>
    </div>
    <div class="layui-form-item" style="text-align: center">
        <button type="button" lay-submit lay-filter="addsave" class="layui-btn layui-btn-sm">保存</button>
        <button type="button" class="layui-btn layui-btn-sm" name="addcancel">取消</button>
    </div>
</div>


<!--修改表单-->
<div style="display: none" id="editWin" lay-filter="editWin" class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label" type="hidden" >id</label>
        <div class="layui-input-inline">
            <input type="text" name="id" required lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
            <!--表单验证：http://layui.xhcen.com/doc/dataForm.html#verify-->
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline">
            <input type="text" name="name" required lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
            <!--表单验证：http://layui.xhcen.com/doc/dataForm.html#verify-->
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">原价</label>
        <div class="layui-input-inline">
            <input type="text" name="price" placeholder="原价" autocomplete="off" class="layui-input" readonly style="color:#439D92">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" required lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">简介</label>
        <div class="layui-input-inline">
            <input type="text" name="info" required lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属类</label>
        <div class="layui-input-inline">
            <select name="category_id">
                <option value="-1">请选择分类</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-inline">
            <img src="easyfile/upload.png" _id="addupload" style="width: 100px;height: 100px;cursor: pointer">
            <input type="hidden" _id="addimgurl" name="defaultimg" lay-verify="easyimg">
        </div>
    </div>
    <div class="layui-form-item" style="text-align: center">
        <button type="button" lay-submit lay-filter="editsave" class="layui-btn layui-btn-sm">保存</button>
        <button type="button" class="layui-btn layui-btn-sm" name="cancel">取消</button>
    </div>
</div>



<div style="display: none" id="imgWin" lay-filter="imgWin" class="layui-form">
    <input type="hidden" name="Tgoodsid">
    <button type="button" id="uploadBTN" class="layui-btn">上传</button>
    <div id="imgbox"></div>
</div>




<script src="layui/layui.all.js"></script>

<script>
    const $ = layui.$;
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const upload = layui.upload;

    //行内按钮监听事件
    table.on("tool(datalist)", function (obj) {
        //被点击按钮的lay-event属性
        let event=obj.event;
        //被点击按钮所在行的数据
        let data = obj.data;
        if(event=='del'){
            //防止误操作
            layer.confirm("确认删除？",function(index){
                //点击确认后执行函数
                layer.close(index);
                $.ajax({
                    url:"goods/del",
                    data:{id:data.id},
                    success:function(result){
                        //成功后提示信息
                        layer.msg("删除成功",{icon:6,time:1000});
                        //刷新表格数据，并且跳转到第一页
                        table.reload("datalist",{page:{curr:1}});
                    }
                })
            })
        }else if(event=='edit'){
            getParent();
            //回显表单数据
            form.val("editWin",data);
            // console.log(data);
            //回显图片
            $("[_id='addupload']").attr("src",data.defaultimg);
            layer.open({
                type: 1,
                tittle:'编辑商品',
                area: ['400px', '400px'],
                content:$("#editWin")
            });
        }else if(event=='manage'){
            imgreload(data.id);
            layer.open({
                type: 1,
                tittle:'编辑商品',
                area: ['400px', '400px'],
                content:$("#imgWin")
            });
        }
    });

    function imgreload(id){
        $("[name='Tgoodsid']").val(id);
        $("#imgbox").empty();
        $.ajax({
            url:"goods/getImgByGoodsid",
            data:{goodsid:id},
            success:function(img){
                if(img.length>0){
                    for(let i=0;i<img.length;i++){
                        $("#imgbox").append("<div><img src='"+img[i].imgurl+"' style='width: 100px;height: 100px;cursor: pointer' onclick='delimg("+img[i].id+")'></div>");
                    }
                }
            }
        });
    }

    //头部按钮监听事件
        //打开窗口前，查询所有父级分类，将其添加在下拉框中
    function getParent(){
        $.ajax({
            url:"goods/getparent",
            data:{category_id:-1},
            async:false,
            success:function(result) {
                // console.log(result);
                $("[name='category_id']").empty();
                $("[name='category_id']").append("<option value=\'null\' disabled selected>请选择分类：</option>")
                for(let i=0;i<result.length;i++){
                    $("[name='category_id']").append("<option value='"+result[i].id+"'>"+result[i].name+"</option>")
                }
                form.render('select');
            }
        });
    }

    table.on("toolbar(datalist)",function(obj){
        form.val("addWin", {pid:'-1', name:''});
        let event=obj.event;
        if(event=="add"){
            getParent();
            $("[_id='addupload']").attr("src","easyfile/upload.png");
            layer.open({
                type: 1,
                tittle:'新增分类',
                area: ['400px','400px'],
                content: $('#addWin')
            })
        }else if(event=="check"){
            //获取输入框中的数据
            let text=$("[name='text']").val();
            //发送到后端  layui表格加载
            table.reload("datalist",{where:{'text':text},page:{curr:1}});

            $("[name='text']").val(text);
        }
    })

    // 新增保存提交按钮事件
    form.on("submit(addsave)",function(data){
        console.log("--表单提交，并验证通过--");
        console.log(data.field);
        console.log(data);
        //发送ajax提交数据
        $.ajax({
            url: "goods/add",
            data:data.field,
            success:function(res){
                //关闭掉本窗口
                layer.closeAll();
                //提示成功
                layer.msg("添加成功",{icon:3,time:1800});
                //刷新表格
                table.reload('datalist');  //table标签的lay-filter属性
            }
        });
        return false;       //禁止表单提交（已经用ajax提交了，不用表格再提交了）
    });


    form.on("submit(editsave)",function(data){
        //data.field表单里的数据
        console.log(data.field);
        $.ajax({
            url: "goods/edit",
            data:data.field,
            success:function(res){
                layer.closeAll();
                layer.msg("修改成功",{icon:3,time:1800});
                table.reload('datalist');
            }
        });
        return false;
    });

    //自定义表单验证规范
    form.verify({
        easyimg:function(value,item){
            //value:表单组件中填入得知
            //item：对应的表单组件
            console.log(value,item);
            if(!value){
                // console.log(1);
                return "必须上传图片";
            }
        }
    });

    //文件上传
    upload.render({
        elem:"[_id='addupload']",
        url:'file/upload',
        done: function(result){
            //上传成功,返回的是一个什么结果?
            //res.data[0].src(文件上传地址)
            // console.log(result);
            let url=result.data[0].src;
            $("[_id='addupload']").attr("src",url);
            $("[_id='addimgurl']").val(url);
        },
        error:function(res){
            // console.log(res);
            layer.msg("上传失败",{icon:2});
        }

    });

    //轮播图上传
    upload.render({
        elem:"#uploadBTN",
        //     指定一个选择器
        url:'file/upload',
        //     上传到哪
        done: function(res){
            console.log(res);
            let src=res.data[0].src;
            let goodsid=$("[name='Tgoodsid']").val();
            $.ajax({
                url:"goods/insertImg",
                data:{goodsid:goodsid,imgurl:src},
                success:function(result){
                    imgreload(goodsid);
                    layer.msg("成功上传"+result+"张图片");
                }
            });
        },
        error: function(){
            layer.msg("文件上传异常，可能是由于文件过大造成的");
        }
    });

    function delimg(id){
        layer.confirm("确认删除此图片？",function(index){
            $.ajax({
                url:"goods/delImgById",
                data:{id:id},
                success:function(res){
                    imgreload(id);
                    layer.close(index);
                    layer.msg("成功删除"+res+"张图片");
                }
            });
        })

    }



</script>
</body>
</html>